// component/statisticiansTable/statisticiansTable.js
const app = getApp();
Component({

  /**
   * 组件的属性列表
   */
  properties: {
    list: {
      type: Array,
      value: []
    },
    addUrl: {
      type: String,
      value: ''
    },
    updateUrl: {
      type: String,
      value: ''
    },
    deleteUrl: {
      type: String,
      value: ''
    },
    title: {
      type: String,
      value: ''
    },
    dataTotal: {
      type: Number,
      value: 0
    },
    dataMoney: {
      type: Number,
      value: 0
    },
    classifyList: {
      type: Array,
      value: []
    },
    isOpen: {
      type: Boolean,
      value: false
    },
    admin: {
      type: Number,
      value: 0
    },
    allChecked: {
      type: Boolean,
      value: false
    },
    ids: {
      type: String,
      value: ''
    }
  },

  /**
   * 组件的初始数据
   */
  data: {
    isMoney: false,
    money: '',
    reason: '',
    classify: '',
    dictCode: '',
    index: '',
    isDisableIndex: '',
    form: {
      money: '',
      dictCode: '',
      nickName: '',
      createTime: '',
      updateTime: '',
      reason: '',
      isDisable: ''
    },
    searchIndex: '',
    calendarShow: false,
    minDate: new Date(2023, 1, 1).getTime(),
    maxDate: new Date().getTime() + 1000 * 60 * 60 * 24,
    date: '',
    isDisableList: [
      { dictCode: 0, dictValue: '禁用' },
      { dictCode: 1, dictValue: '启用' }
    ]
  },

  /**
   * 组件的方法列表
   */
  methods: {
    switchPayeeChange(e) {
      const idObj = {};
      if (this.properties.title == '预付' || this.properties.title == '耗损') idObj.financeId = 0;
      wx.showLoading();
      wx.request({
        url: `${app.globalData.baseUrl}${this.properties.updateUrl}`,
        method: "POST",
        data: { id: e.currentTarget.dataset.id, isDisable: e.detail ? '1' : '0', ...idObj },
        header: {
          "Content-Type": "application/json",
          'token': wx.getStorageSync('token'),
        },
        success: (res) => {
          wx.hideLoading();
          if (res.data.code == 0) {
            wx.showToast({
              title: res.data.msg || '报错啦！',
              duration: 2000
            })
            this.triggerEvent('change', 1);
          } else if (res.data.code == 500) {
            wx.showToast({
              title: res.data.msg || '报错啦！',
              icon: 'error',
              duration: 2000
            })
          } else {
            wx.showToast({
              title: '系统错误，请重新登录',
            })
          }
        },
        fail: () => {
          wx.hideLoading();
          wx.showToast({
            title: '系统错误',
          });
          _that.setData({ loading: false });
        }
      })
    },

    onIsDisableSearch(e) {
      const mchObj = this.data.isDisableList[e.detail.value];
      this.setData({
        isDisableIndex: e.detail.value,
        form: {
          ...this.data.form,
          isDisable: mchObj.dictCode,
        }
      });
    },

    deleteRow(e) {
      let id = e.currentTarget.dataset.id;
      if (!id) {
        wx.showModal({
          content: '请在列表选择需要删除的数据！',
          showCancel: false,
        });
        return;
      }
      const that = this;
      wx.showModal({
        content: '确认删除吗？',
        success: function (sm) {
          if (sm.confirm) {
            wx.request({
              url: `${app.globalData.baseUrl}${that.properties.deleteUrl}${id}`,
              method: "GET",
              header: {
                'token': wx.getStorageSync('token'),
                "Content-Type": "application/json"
              },
              success: (res) => {
                if (res.data.code == 0) {
                  that.triggerEvent('change', 1);
                  wx.showToast({
                    title: '成功删除',
                  });
                } else {
                  wx.showToast({
                    title: res.data.msg || '报错啦！',
                    duration: 2000
                  })
                }
              }
            })
          } else {
            console.log('用户点击取消');
          }
        }
      })
    },

    onMoneyShow() {
      this.setData({
        isMoney: true,
        money: '',
        reason: '',
        classify: '',
        dictCode: '',
      });
    },

    onMoneyHidden() {
      this.setData({ isMoney: false });
    },

    onMoneyChange(e) {
      this.setData({ money: e.detail });
    },

    onMoneySearch(e) {
      this.setData({
        form: {
          ...this.data.form,
          money: e.detail
        }
      });
    },

    onReasonSearch(e) {
      this.setData({
        form: {
          ...this.data.form,
          reason: e.detail
        }
      });
    },

    onReasonChange(e) {
      this.setData({ reason: e.detail });
    },

    onClassifyChange(e) {
      const mchObj = this.properties.classifyList[e.detail.value];
      this.setData({
        index: e.detail.value,
        classify: mchObj.dictValue,
        dictCode: mchObj.dictCode
      });
    },

    addMoney() {
      const { money, reason, dictCode } = this.data;
      if (!money) {
        wx.showToast({
          title: `请填写${this.properties.title}金额`,
          icon: 'error',
        })
        return;
      }
      const reg = /^-?\d+(.\d{1,2})?$/
      if(!reg.test(money)) {
        wx.showToast({
          title: `${this.properties.title}金额有误`,
          icon: 'error',
        })
        return;
      }
      if (!dictCode) {
        wx.showToast({
          title: `请选择归类`,
          icon: 'error',
        })
        return;
      }
      const idObj = {};
      if (this.properties.title == '预付' || this.properties.title == '耗损') idObj.financeId = 0;
      wx.showLoading();
      wx.request({
        url: `${app.globalData.baseUrl}${this.properties.addUrl}`,
        method: "POST",
        data: {
          money: parseFloat(money).toFixed(2),
          reason,
          classify: dictCode,
          ...idObj
        },
        header: {
          "Content-Type": "application/json",
          'token': wx.getStorageSync('token'),
        },
        success: (res) => {
          wx.hideLoading();
          if (res.data.code == 0) {
            wx.showToast({
              title: '添加成功',
            });
            this.triggerEvent('change', 1);
            this.onMoneyHidden();
          } else if (res.data.code == 500) {
            wx.showToast({
              title: res.data.msg || '报错啦！',
              icon: 'error',
              duration: 2000
            })
          } else {
            wx.showToast({
              title: '系统错误，请重新登录',
            })
          }
        },
        fail: () => {
          wx.hideLoading();
          wx.showToast({
            title: '系统错误',
          });
          _that.setData({ loading: false });
        }
      })
    },

    searchClick() {
      this.setData({ isOpen: !this.data.isOpen });
    },

    onDisplay() {
      this.setData({ calendarShow: true });
    },

    onRangeClose() {
      this.setData({ calendarShow: false });
    },
    onMoneySearch(e) {
      this.setData({
        form: {
          ...this.data.form,
          money: e.detail
        }
      });
    },

    onNickSearch(e) {
      this.setData({
        form: {
          ...this.data.form,
          nickName: e.detail
        }
      });
    },

    onClassifySearch(e) {
      const mchObj = this.properties.classifyList[e.detail.value];
      this.setData({
        searchIndex: e.detail.value,
        form: {
          ...this.data.form,
          classify: mchObj.dictCode,
        }
      });
    },

    onConfirm(event) {
      const [start, end] = event.detail;
      const endTime = new Date(end).getTime();
      this.setData({
        calendarShow: false,
        form: {
          ...this.data.form,
          createTime: `${this.formatDate(start)} 00:00:00`,
          updateTime: `${this.formatDate(endTime)} 00:00:00`,
        },
        date: `${this.formatDate(start)} - ${this.formatDate(end)}`,
      });
    },

    formatDate(date) {
      date = new Date(date);
      let month = date.getMonth() + 1;
      let day = date.getDate();
      if (month < 10) {
        month = '0' + month;
      }
      if (day < 10) {
        day = '0' + day;
      }
      return `${date.getFullYear()}-${month}-${day}`;
    },

    onReset() {
      this.setData({
        form: {
          money: '',
          dictCode: '',
          nickName: '',
          createTime: '',
          updateTime: '',
          isDisable: ''
        },
        searchIndex: '',
        date: '',
        isDisableIndex: ''
      });
      this.triggerEvent("onSearch", {})
    },

    onSearch() {
      this.triggerEvent("onSearch", this.data.form)
    },

    onExport() {
      this.triggerEvent("onExport")
    },

    onAllChange() {
      const arr = [...this.properties.list];
      let ids = [];
      arr.forEach(item => {
        if (this.properties.allChecked) {
          item.isCheckBox = false;
        } else {
          item.isCheckBox = true;
        }
        if (item.isCheckBox) ids.push(item.id);
      });
      this.triggerEvent("onAllChange", {
        allChecked: !this.properties.allChecked,
        list: arr,
        ids
      });
    },
    onCheckedBox(e) {
      const arr = [...this.properties.list];
      let flag = false;
      let ids = [];
      arr.forEach(item => {
        if (e.currentTarget.dataset.id == item.id) {
          item.isCheckBox = !item.isCheckBox;
        }
        if (!item.isCheckBox) flag = true;
        if (item.isCheckBox) ids.push(item.id);
      });
      this.triggerEvent("onAllChange", {
        allChecked: flag ? false : true,
        list: arr,
        ids
      });
    },
  }
})